package com.jcfk.system.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class CipherUtils {
    private static final String ALGORITHM = "AES";
    private static final String CIPHER_TYPE = "AES/ECB/PKCS5Padding";

    public CipherUtils() {
    }

    /**
     * 加密
     *
     * @param strToEncrypt
     * @param key
     * @return
     */
    public static String encrypt(String strToEncrypt, String key) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
            byte[] encryptedBytes = cipher.doFinal(strToEncrypt.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception var5) {
            System.out.println("Error while encrypting: " + var5.toString());
            return null;
        }
    }

    /**
     * 解密
     *
     * @param strToDecrypt
     * @param key
     * @return
     */
    public static String decrypt(String strToDecrypt, String key) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(strToDecrypt));
            return new String(decryptedBytes);
        } catch (Exception var5) {
            System.out.println("Error while decrypting: " + var5.toString());
            return null;
        }
    }

    public static SecretKey getSecretKey(String key) {
        byte[] decodedKey = Base64.getDecoder().decode(key);
        SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, ALGORITHM);
        return originalKey;
    }
}
